<template>
	<view class="">

		<view class="margin-top-sm">
			<!-- 搜索框 -->
			<view style="margin-top: 20rpx;display: flex;">
				<view style="width: 150rpx;margin: 0rpx 10px;">
					<button class="login-btn cu-btn block bg-white" @click="showMore">更多</button>
				</view>
				<view style="flex: 1;margin: 0rpx 10px;">
					<uni-easyinput ConfirmType="search" type="text" suffixIcon="search" confirmType="search"
						v-model="queryFrom.student_name" placeholder="学生姓名" @iconClick="init" @confirm="init">
					</uni-easyinput>
				</view>
				<view style="width: 150rpx;margin: 0rpx 10px;">
					<button class="login-btn cu-btn block bg-blue" @click="init">查询</button>
				</view>
			</view>
			<view style="display: flex;" class="bg-white padding-sm margin-sm radius">
				<view style="flex:1;text-align: center;border: 1px solid #ccc;border-radius: 5px"
					@click="handleClick(-1)" class=" juzhong radius ">前一天
				</view>
				<view style="flex:1;text-align: center;margin-left: 10rpx;margin-right: 10rpx;">
					<view class="font-13">{{dateToWeek(queryFrom.startClassDate_EQ)}}</view>
					<view class="font-11">

						<uni-datetime-picker type="date" :clear-icon="false" v-model="queryFrom.startClassDate_EQ"
							size="mini" @change="handleClick(0)" />
					</view>
				</view>
				<view style="flex:1;text-align: center;border: 1px solid #ccc;border-radius: 5px"
					@click="handleClick(1)" class=" juzhong radius">后一天</view>
			</view>
		</view>

		<view class="navbar">
			<view class="font-12 juzhong  " style="color: #999;" v-if="total>0">
				第{{queryFrom.pageNo}}页，共计{{total}}条
			</view>



			<view style="display: flex;" class="margin-left-sm margin-top-xs" v-if="status!=null">
				<button :disabled="from.checkbox.length==0" @click="caozuoPL(4)"
					class=" cu-btn block bg-purple  font-12 fade-animation" style="margin-right: 10rpx;"
					v-if="$perms('system_scheduletimetable_quxiaopaike')&&status==0">取消</button>

				<button :disabled="from.checkbox.length==0" @click="truancy(null,false,0)"
					class=" cu-btn block bg-pink disabled   font-12 fade-animation" style="margin-right: 10rpx;"
					v-if="$perms('system_scheduletimetable_signOk')&&status==0">旷课</button>



				<button :disabled="from.checkbox.length==0" @click="cancelTruancy(null,true)"
					class=" cu-btn block bg-pink  font-12 fade-animation" style="margin-right: 10rpx;"
					v-if="$perms('system_scheduletimetable_quxiaopaike')&&status==2">取消旷课</button>

				<button :disabled="from.checkbox.length==0" @click="cancelsSign(null,true)"
					class=" cu-btn block bg-blue  font-12 fade-animation" style="margin-right: 10rpx;"
					v-if="$perms('system_scheduletimetable_quxiaopaike')&&status==1">取消签到</button>

				<button :disabled="from.checkbox.length==0" @click="revertCancels(null)"
					class=" cu-btn block bg-blue  font-12" style="margin-right: 10rpx;"
					v-if="$perms('system_scheduletimetable_quxiaopaike')&&status==4">恢复排课</button>

				<button v-if="$perms('system_scheduletimetable_signOk_super')&&status==0"
					:disabled="from.checkbox.length==0" @click="signOk(null,true,1)"
					class=" cu-btn block bg-grey  font-12 fade-animation" style="margin-right: 10rpx;"> 超签
				</button>
				<button :disabled="from.checkbox.length==0" @click="caozuoPL(1)"
					class=" cu-btn block bg-blue disabled   font-12 fade-animation" style="margin-right: 10rpx;"
					v-if="$perms('system_scheduletimetable_signOk')&&status==0">
					签到</button>
			</view>

			<view style="height: 4px;background-color: #ededed;margin: 10rpx 0px;"></view>

		</view>

		<view v-if="list.length==0" class="margin-top-sm">
			<blues-empty img="msg" text="暂无数据">

			</blues-empty>
		</view>
		<view :class="{'bg-white  padding-sm   margin-bottom-sm':true,'background-text-shengxiao':item.status==1,'background-text-2':item.status==0,
			'background-text-shixiao':item.status==4,'background-text-4':item.status==2}" v-for="(item,index) in list"
			@click="onClick(item)" class="list-item" :style="{animationDelay:gets(index)}">
			<view style="z-index:3;position: relative;">
				<view style="display: flex;">
					<view style="width: 40rpx;margin-right: 10rpx;" class="juzhong">
						<view style="border:1px solid #999 ;width: 35rpx;height: 35rpx;border-radius: 5px;">
							<uni-icons type="checkmarkempty" size="15" style="color: #999;"
								v-if="item.checkbox"></uni-icons>
						</view>
					</view>
					<view style="flex: 2;">
						<view style="font-weight: bold;">{{item.customerModel.student.name}}</view>
						<view class="font-12 margin-top-xs">
							{{$getDictNameByValue("offline_class_name", item.offlineClassName)}}
						</view>
						<view class="font-12 margin-top-xs "> {{item.startClassDate}}</view>
					</view>


					<view style="flex: 2;">
						<view class="margin-right-xs font-12" style="z-index: 3;">
							老师名称
						</view>
						<view class="font-12 margin-top-xs" style="">
							1课时/222元
						</view>
						<view class="font-12 margin-top-xs" style="">
							144标准包JC-转移
						</view>
					</view>


					<view style="flex: 1;">
						<view class="margin-right-xs font-12" style="z-index: 3;">
							{{ $getDictNameByValue('checkInStatus', item.status) }}
						</view>
						<view class="font-12 margin-top-xs" style="">
							常规课/跟班
						</view>
						<view class="font-12 margin-top-xs" style="">
							{{ shijianduan(item.sysTimeSlotId) }}
						</view>
					</view>

				</view>
			</view>
		</view>

		<!-- 查询更多 -->
		<customerQuery @refresh="init" ref="customerQuery">
			<template v-slot:default="slotProps">

				<uni-forms-item label="课程名称">
					<uni-data-select v-model="queryFrom.offlineClassName_EQ"
						:localdata="slotProps.dict.offline_class_name" placeholder="选择课程名称"></uni-data-select>
				</uni-forms-item>
				<uni-forms-item label="排课状态">
					<uni-data-checkbox style="width: 100%;" mode="button" v-model="queryFrom.status_EQ"
						:localdata="slotProps.dict.checkInStatus"
						:map="{text:'dictName',value:'dictValue'}"></uni-data-checkbox>
				</uni-forms-item>
				<uni-forms-item label="上课日期">
					<uni-datetime-picker v-model="queryFrom.startClassDate_EQ" type="daterange" />
				</uni-forms-item>



			</template>

		</customerQuery>

	</view>

</template>

<script>
	import {
		getShiJianDuanById,
		formatterUserName
	} from "@/utils/common";
	import {
		cancelsSign,
		cancelTruancy,
		doDelete,
		doExportExcel,
		doInsert,
		getList,
		getListByCustomerIdAndDate,
		signOk,
		truancy
	} from "@/api/system/academicAffairsCenter/scheduleTimetable/SysScheduleTimetableManagementApi";
	import addStudentVue from "@/pages/tenantSet/academicAffairsCenter/offlineClass/addStudent.vue";
	import {
		formatTime,
		isNull,
		getChineseWeekday,
		formateDate,
		dateShifting
	} from '@/utils/validate'
	import customerQuery from "@/pages/common/customerQuery/customerQuery.vue"

	export default {
		components: {
			customerQuery
		},
		data() {
			return {
				queryFrom: {
					pageNo: 1,
					pageSize: 10,
					startus_EQ: null,
					startClassDate_ORDER: "DESC",
					customerId_EQ: null,
					startClassDate_EQ: formateDate(new Date(), 'yyyy-MM-dd')
				},
				from: {
					checkbox: []
				},
				status: null,
				total: 0,
				list: []
			}
		},
		mounted() {


		},
		onLoad(op) {
			if (op.customerId != null) {
				this.queryFrom.customerId_EQ = op.customerId
			}
			this.init()
		},
		// 触底事件 - 上拉加载
		onReachBottom() {
			// 加判断： 页码数 * 每一页获取数据的条数 >= 总条数，如果符合条件说明数据已经全部加载完毕
			if (this.queryFrom.pageNo * this.queryFrom.pageSize >= this.total) {

				return
			} else {

				this.queryFrom.pageNo++ // 每触发一次触底事件，页码加1
				this.listAdd() // 请求接口，获取数据  
			}
		},
		methods: {
			handleClick(i) {

				if (i == 1) {
					this.queryFrom.startClassDate_EQ = dateShifting(this.queryFrom.startClassDate_EQ, 1);
				}
				if (i == -1) {
					this.queryFrom.startClassDate_EQ = dateShifting(this.queryFrom.startClassDate_EQ, -1);
				}
				if (i == 0) {
					this.queryFrom.startClassDate_EQ
				}


				this.init()
			},
			onClick(item) {

				this.checkboxChange2(item)
			},

			checkboxChange2(data) {


				if (this.status != null && this.status != data.status) {
					uni.showToast({
						title: "所选状态必须一致",
						icon: "none"

					})
					return
				}


				// 检查数组中是否存在元素1
				if (this.from.checkbox.includes(data.id)) {
					// 如果存在，则删除元素1
					this.from.checkbox = this.from.checkbox.filter(item => item != data.id);
				} else {
					// 如果不存在，则添加元素1
					this.from.checkbox.push(data.id);
				}



				if (data.checkbox == null || data.checkbox == false) {

					data.checkbox = true
					if (this.status == null) {
						this.status = data.status
					}
				} else {

					data.checkbox = false
				}



				if (this.from.checkbox.length == 0) {
					this.status = null
				}
				console.log(this.from.checkbox);
				this.$forceUpdate();

			},
			showMore() {
				this.$refs["customerQuery"].open(this.queryFrom);
			},
			shijianduan(id) {
				return getShiJianDuanById(id)
			},
			init() {
				this.list = []
				this.total = 0
				this.queryFrom.pageNo = 1
				//查询合同信息
				this.fetchData()
			},
			listAdd() {
				//查询合同信息
				this.fetchData()
			},
			dateToWeek(data) {
				return getChineseWeekday(data)
			},
			async fetchData() {

				if (!isNull(this.queryFrom.id_LIST)) {
					await this.fetchDataByIds()
					return
				}

				this.status = null
				this.from.checkbox = []

				const {
					data
				} = await getList(this.queryFrom);
				if (!isNull(data)) {
					this.list = this.list.concat(data.rows)

					this.total = data.total;
				}

			},


			async fetchDataByIds(ids) {

				if (this.queryFrom.id_LIST.split(',') == 1) {
					this.queryFrom.id_LIST = null
					this.queryFrom.id_EQ = this.queryFrom.id_LIST
				}
				this.status = null
				this.from.checkbox = []
				const {
					data
				} = await getList(this.queryFrom);
				if (!isNull(data)) {

					let array1 = this.list
					let array2 = data.rows


					for (let j = 0; j < array2.length; j++) {
						let item2 = array2[j];
						item2.checkbox = null
						let found = false;
						for (let i = 0; i < array1.length; i++) {
							let item1 = array1[i];


							if (item1.id == item2.id) {
								// 如果在arr2中找到相同id的对象，则使用该对象覆盖
								array1[i] = item2
								found = true;

								break; // 找到后跳出内层循环
							}
						}
						if (!found) {

							// 如果在arr2中没有找到相同id的对象，则添加原始对象
							array1.push(item2);
						}

					}
					this.list = array1;
					console.log(this.list[0].status);
					this.queryFrom.id_LIST = null
					this.queryFrom.id_EQ = null
					// this.list = mergedArray
					this.queryFrom.id_LIST = null
					this.total = data.total;
				}
				this.$forceUpdate();
			},

			//批量签到或者取消
			caozuoPL(type) {

				let _this = this
				if (type == 1) {
					uni.showModal({
						title: "签到",
						content: "确认签到吗",
						cancelText: "取消",
						confirmText: "确认",
						success: async function(res) {
							if (res.confirm) {
								_this.signOk(null, false, 1)
							} else if (res.cancel) {

							}
						}
					})

				}
				//批量取消
				if (type == 4) {

					uni.showModal({
						title: "取消排课",
						content: "请选择跟班类型",
						cancelText: "插班",
						confirmText: "跟班",
						success: async function(res) {
							if (res.confirm) {
								for (const s of _this.from.checkbox) {
									//批量取消
									if (type == 4) {
										_this.cancelCourseArrange2(s, 1)
										await _this.delay(2000);
									}
								}
							} else if (res.cancel) {
								for (const s of _this.from.checkbox) {
									//批量取消
									if (type == 4) {
										_this.cancelCourseArrange2(s, 2)
										await _this.delay(2000);
									}
									await _this.delay(1000);
								}
							}
						}
					})


				}

			},
			delay(ms) {
				uni.showLoading({
					title: "处理中"
				})
				return new Promise(resolve => setTimeout(resolve, ms));
			},
			//查看合同
			tiaozhuanhetong(id) {
				window.open("/#/contract?id=" + id);
			},
			tableAddClass({
				row,
				rowIndex
			}) {
				if (row.status == 4) {
					return 'tr-red';
				}
				return '';
			},

			rowStyle({
				row,
				rowIndex
			}) {

				if (row.status == 4) {
					let styleObj = {}
					styleObj.background = "rgb(255,217,217)"
					return styleObj;
				}


			},
			gets(index) {
				if (index < 10) {
					return index * 0.2 + 's'
				} else {
					return (index % 10 + 1) * 0.2 + 's'
				}

			},
			async truancy(row, type) {
				//选择要旷课的课程
				var truancydialogList = this.getselectDateList()

				for (const signdialogListElement of truancydialogList) {
					let {
						msg
					} = await truancy({
						id: signdialogListElement.id
					});
					await this.delay(1000);
				}
				this.queryFrom.id_LIST = truancydialogList.map(obj => obj.id).join(',')
				this.fetchData();


			},
			async cancelTruancy(row) {

				//选择要旷课的课程
				var truancydialogList = this.getselectDateList()

				for (const signdialogListElement of truancydialogList) {
					let {
						msg
					} = await cancelTruancy({
						id: signdialogListElement.id
					});
					await this.delay(1000);
				}
				this.queryFrom.id_LIST = truancydialogList.map(obj => obj.id).join(',')
				this.fetchData();

			},
			setSelectRows(val) {
				this.selectRows = val;
			},
			handleInsert(row) {
				this.$refs["edit"].showEdit({
					"currtype": this.offlineCurriculumType,
					"offlineTimetableId": this.queryForm.offlineTimetableId_EQ,
					"charu": true
				});
			},
			handleUpdate(row) {
				if (row.id) {
					this.$refs["edit"].showEdit(row);
				}
			},
			async cancelCourseArrange2(id, longTerm) {
				const {
					msg
				} = await doDelete({
					id: id,
					longTerm: longTerm
				});
				this.queryFrom.id_LIST = [id]
				this.fetchData();

			},

			async cancelCourseArrange(row, longTerm) {
				row.longTerm = longTerm
				const {
					msg
				} = await doDelete(row);
				this.$baseMessage(msg, "success");
				this.handleDeleteId = null
				this.cancelCourseArrangedialogList = this.cancelCourseArrangedialogList.filter(item => item.id !== row
					.id);
				if (this.cancelCourseArrangedialogList.length == 0) {
					this.cancelCourseArrangedialogVisible = false
					this.queryFrom.id_LIST = [row.id]
					this.fetchData();
				}
			},
			async handleDelete(row, type) {
				this.cancelCourseArrangedialogData.id = row.id
				if (type == 0) {
					this.cancelCourseArrangedialogList = []
					this.cancelCourseArrangedialogVisible = true
					const {
						msg,
						data
					} = await getListByCustomerIdAndDate({
						customerId: row.customerModel.id,
						date: formateDate(new Date(row.startClassDate), 'yyyy-MM-dd')
					});
					var cancelCourseArrangedialogList = data
					for (const signdialogListElement of cancelCourseArrangedialogList) {
						this.cancelCourseArrangedialogList.push({
							id: signdialogListElement.id,
							time: this.shijianduan(signdialogListElement.sysTimeSlotId),
							offlineClassName: this.$getDictNameByValue('offline_class_name',
								signdialogListElement.offlineClassName),
						})
					}
					this.cancelCourseArrangedialogTitle = "请选择《" + row.customerModel.student.name + "》今天需要取消的课程"
				}

			},

			async cancelsSign(row) {

				//选择要旷课的课程
				var truancydialogList = this.getselectDateList()

				for (const signdialogListElement of truancydialogList) {
					console.log(signdialogListElement.id);
					let {
						msg
					} = await cancelsSign({
						id: signdialogListElement.id
					});
					await this.delay(1000);
				}
				this.queryFrom.id_LIST = truancydialogList.map(obj => obj.id).join(',')
				this.fetchData();
			},

			// 获取选中的行
			getselectDateList() {
				let asdf = []
				for (let s of this.from.checkbox) {
					for (let s1 of this.list) {
						if (s1.id == s) {

							asdf.push(s1)
						}
					}
				}

				console.log(asdf.length);
				return asdf
			},
			//签到 先选择要签到的课程  如果只有一个就直接签到 type 0就是选择课程 1就是直接签到
			async signOk(row, isSuper, type) {
				//选择要签到的课程
				let signdialogList = this.getselectDateList()
				if (type === 0) {

				}
				//超级签到
				if (type === 1) {

					for (const signdialogListElement of signdialogList) {
						const {
							msg
						} = await signOk({
							id: signdialogListElement.id,
							isSuper: isSuper
						});

						await this.delay(1000);
					}
					this.queryFrom.id_LIST = signdialogList.map(obj => obj.id).join(',')
					this.fetchData();
				}

			},


			//恢复取消
			async revertCancels(row) {

				let signdialogList = this.getselectDateList()
				for (const signdialogListElement of signdialogList) {
					const {
						msg
					} = await doInsert(signdialogListElement);
					await this.delay(1000);
				}
				this.queryFrom.id_LIST = truancydialogList.map(obj => obj.id).join(',')
				this.fetchData();

			},


		}
	}
</script>

<style lang="scss" scoped>
	.navbar {

		width: 100%;
		background-color: #f1f1f1;
		z-index: 4;
		text-align: center;
		position: -webkit-sticky;
		position: -ms-sticky;

		position: -o-sticky;

		/* 粘性定位*/

		position: sticky;

		left: 0;

		top: 0
	}



	/deep/.uni-date__x-input {
		width: auto;
		height: 30rpx;
		padding-left: 5px;
		position: relative;
		flex: 1;
		line-height: 35rpx;
		font-size: 14px;
		overflow: hidden;
	}

	.el-tabs__item {
		list-style: none;
		font-size: 14px;
		font-weight: 500;
		color: #303133;
	}

	/deep/.uni-date-x {
		.icon-calendar {
			display: none;
		}
	}

	/deep/.uni-date-x--border {
		border: none
	}
</style>